package com.zhidisoft.crm.controller.auth;

import java.util.List;
import java.util.UUID;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhidisoft.crm.dao.ISysUserRolemapper;
import com.zhidisoft.crm.entity.SysUserRole;
import com.zhidisoft.crm.service.ISysRoleService;
import com.zhidisoft.crm.service.ISysUserRoleService;
import com.zhidisoft.crm.service.ISysUserService;
import com.zhidisoft.crm.vo.AjaxVo;
import com.zhidisoft.crm.vo.SysUserRoleVo;
import com.zhidisoft.crm.vo.SysUserVo;

@Controller
@RequestMapping("/auth/user_role")
public class UserRoleController {

	@Autowired
	ISysUserService iSysUserService;
	
	@Autowired
	ISysRoleService iSysRoleService;
	
	@Autowired
	ISysUserRoleService iSysUserRoleService;
	
	@GetMapping("/{id}")
	@ResponseBody
	public ModelAndView userRole(@PathVariable("id") String id){
		ModelAndView mav = new ModelAndView("auth/user_role/form.html", "user", iSysUserService.findId(id));
		
		mav.addObject("roleList", iSysRoleService.selectAll());
		mav.addObject("roleId", iSysUserRoleService.findRoleId(id));
		return mav;
		
	}
	
	@PostMapping("{id}")
	@ResponseBody
	public AjaxVo userRoleSave(SysUserRoleVo sysUserRoleVo,@PathVariable("id") String id,BindingResult result){
		if(result.hasErrors()){
			List<ObjectError> list = result.getAllErrors();
			for (ObjectError objectError : list) {
				return new AjaxVo().setErrorCode("1001").setErrorMsg(objectError.getDefaultMessage());
			}
		}
		
		SysUserRole userRole=new SysUserRole();
		iSysUserRoleService.deleteById(id);
		userRole.setId(UUID.randomUUID().toString().replace("-", ""));
		userRole.setUser_id(id);
		userRole.setRole_id(sysUserRoleVo.getRole_id());
		iSysUserRoleService.save(userRole);
		return new AjaxVo().setErrorCode("0");
	}
}
